// 文章接口
var express = require('express');
var router = express.Router();
const sql = require('../conf/sql.js')
const pool = require('../conf/db.js')

// 病人预约疫苗操作
router.post('/', function (req, res, next) {
  console.log(req.body);
  // index是第几天（day1或day2），whichtime是哪个是时间段（9.30 or 10.30）
  let { type, name, hid, pid, test_name, state, index, whichtime, appoint_time } = req.body
  // let appoint_time = parseInt(Date.now() / 1000)
  // 插入操作
  pool.query(sql.order_medical, [type, name, hid, pid, test_name, appoint_time, state], (err, result) => {
    if (err) {
      next(err)
      return
    }
    // console.log(result);
    // 判断是否插入成功
    if (result.affectedRows == 0) {
      res.json({
        code: 201,
        msg: 'failed',
      })
    } else {
      // 这里要将医院疫苗库存减1，先通过hid查询医院信息，再修改医院某一天库存
      let selectday = 'select * from hospital where id = ?'
      pool.query(selectday, [hid], (err, result) => {
        if (err) {
          next(err)
          return
        }
        console.log(result[0][index]);
        // result[0][index]是查询到的医院 选中天 的数据
        let newstore = JSON.parse(result[0][index])
        // 将 whichtime 这天的库存减1
        newstore[whichtime] = newstore[whichtime] - 1

        pool.query(`update hospital set ${index} = ? where id = ?`, [JSON.stringify(newstore), hid], (err, result) => {
          // console.log(index);
          if (err) {
            console.log(err);
            next(err)
            return
          }
          console.log(result);
          res.json({
            code: 200,
            msg: 'success'
          })
        })
      })

    }

  })

});

// 查看检测结果
router.get('/appointment_report', function (req, res, next) {
  let {pid} = req.query
  pool.query(sql.appointment_report, [pid], (err, result) => {
    if (err) {
      next(err)
      return
    }
    if (result.length == 0) {
      res.json({
        code: 201,
        msg: 'failed'
      })
    }else {
      res.json({
        code: 200,
        msg: 'success',
        data: result
      })
    }
   


  })
})

// 查看检测结果详情
router.get('/reportdetail', function (req, res, next) {
  let {pid, appoint_time} = req.query
  pool.query(sql.reportdetail, [pid, appoint_time], (err, result) => {
    if (err) {
      next(err)
      return
    }
    if (result.length == 0) {
      res.json({
        code: 201,
        msg: 'failed'
      })
    }else {
      res.json({
        code: 200,
        msg: 'success',
        data: result[0]
      })
    }
  })
})
module.exports = router;
